package com.hxzy.interceptor;

import com.alibaba.fastjson.JSON;
import com.hxzy.pojo.Result;
import com.hxzy.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author wzm
 * @create 2024-03-11 15:28
 * project_name:JavaWeb2401
 * @Description
 */
//用于登录检验的拦截器
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取url
        //2.判断是否是登录 login

        //3.获取token
        String token = request.getHeader("Token");
        log.info("请求头中的token,{}", token);

        //4.判断token是否为空  返回not_login
        if(!StringUtils.hasLength(token)){
           log.info("token不存在");
           //创建错误响应对象
            Result result = Result.error("NOT_LOGIN");
            String jsonString = JSON.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);

            return false;//不放行
        }


        //5.解析token 出错
        try {
            JwtUtils.parseJwt(token);
        }catch (Exception e){
            log.info("解析令牌失败");
            //创建错误响应对象
            Result result = Result.error("NOT_LOGIN");
            String jsonString = JSON.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);

            return false;//不放行
        }

        //6.直接放行
        return true;
    }
}
